﻿using Dal;
using Entity;
using Entity.DTO;
using IDal;
using Org.BouncyCastle.Cms;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Principal;

namespace Bll
{
    /// <summary>
    /// 订单业务逻辑层
    /// </summary>
    public class OrderBll : IOrderBll
    {
        IOrderDal _ordersDal;
        IUserInfoDal _userInfoDal;
        IOrderMaterialDal _orderMaterialDal;
        IMaterialDal _materialDal;
        IClassificationDal _classificationDal;


        public OrderBll(IOrderDal ordersDal, IUserInfoDal userInfoDal, IOrderMaterialDal orderMaterialDal, IMaterialDal materialDal, IClassificationDal classificationDal)
        {
            _ordersDal = ordersDal;
            _userInfoDal = userInfoDal;
            _orderMaterialDal = orderMaterialDal;
            _materialDal = materialDal;
            _classificationDal = classificationDal;
        }


        /// <summary>
        /// 创建订单
        /// </summary>
        /// <returns></returns>
        public bool CreateOrder(string customerName, string customerPhone, string customerAddress, double area, string agentName, string agentPhone, DateTime startTime, DateTime endTime, string designerId, string userId, out string msg)
        {
            //获取当前时间的字符串
            string nowStr = DateTime.Now.ToString("yyyyMMddHHmmss");
            //组合成新的标题
            string title = $"{nowStr}-{customerName}-{customerAddress}";

            Order orders = _ordersDal.GetDbSet()
                .Where(d => d.Title == title).FirstOrDefault();

            if (orders != null)
            {
                msg = "订单已经存在";
                return false;
            }

            Order entity = new Order();
            //创建guid 赋值给订单id，目的是保证id唯一
            entity.Id = Guid.NewGuid().ToString();
            entity.Title = title;
            entity.CustomerName = customerName;
            entity.CustomerPhone = customerPhone;
            entity.CustomerAddress = customerAddress;
            entity.Area = area;
            entity.AgentName = agentName;
            entity.AgentPhone = agentPhone;
            entity.StartTime = startTime;
            entity.EndTime = endTime;
            entity.DesignerId = designerId;
            entity.CreatorId = userId;
            entity.CreateTime = DateTime.Now;

            //调用数据访问层创建订单
            bool isSuccess = _ordersDal.CreateEntity(entity);

            if (isSuccess)
            {
                msg = "成功";
            }
            else
            {
                msg = "失败";
            }
            return isSuccess;
        }


        /// <summary>
        /// 软删除订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteOrder(string id)
        {
            Order orders = _ordersDal.GetDbSet().FirstOrDefault(u => u.Id == id);
            if (orders == null)
            {
                return false;
            }

            orders.IsDelete = true;

            return _ordersDal.UpdateEntity(orders);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteOrders(List<string> ids)
        {
            foreach (var id in ids)
            {
                Order orders = _ordersDal.GetDbSet().FirstOrDefault(u => u.Id == id);
                if (orders == null)
                {
                    return false;
                }

                orders.IsDelete = true;

                _ordersDal.UpdateEntity(orders);
            }

            return true;
        }


        /// <summary>
        /// 根据订单id获取订单信息
        /// </summary>
        /// <param name="ordersId"></param>
        /// <returns></returns>
        public object GetOrderById(string ordersId)
        {
            var data = (from o in _ordersDal.GetDbSet().Where(n => n.Id == ordersId && !n.IsDelete)  //订单
                        select new
                        {
                            o.Id,
                            o.Title,
                            o.CustomerName,
                            o.CustomerPhone,
                            o.CustomerAddress,
                            o.Area,
                            o.AgentName,
                            o.AgentPhone,
                            o.StartTime,
                            o.EndTime,
                            o.DesignerId,
                            o.CreateTime
                        }).ToList().Select(o => new
                        {
                            o.Id,
                            o.Title,
                            o.CustomerName,
                            o.CustomerPhone,
                            o.CustomerAddress,
                            o.Area,
                            o.AgentName,
                            o.AgentPhone,
                            StartTime = o.StartTime.ToString("yyyy-MM-dd"),
                            EndTime = o.EndTime.ToString("yyyy-MM-dd"),
                            o.DesignerId,
                            CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                        }).FirstOrDefault();

            return data;
        }


        /// <summary>
        /// 获取订单集合
        /// </summary>
        public object GetOrderList(string title, int page, int limit, out int count)
        {
            //左连接
            var queryable = from n in _ordersDal.GetDbSet().Where(n => !n.IsDelete)  //订单
                            join u in _userInfoDal.GetDbSet().Where(n => !n.IsDelete)
                            on n.DesignerId equals u.Id into uTemp
                            from u2 in uTemp.DefaultIfEmpty()
                            select new
                            {
                                n.Id,
                                n.Title,
                                n.CustomerName,
                                n.CustomerPhone,
                                n.CustomerAddress,
                                n.Area,
                                n.AgentName,
                                n.AgentPhone,
                                n.StartTime,
                                n.EndTime,
                                Designer = u2.UserName,
                                n.CreateTime
                            };


            //IQueryable<Orders> queryable = _ordersDal.GetOrderssDbSet().Where(u => !u.IsDelete).OrderByDescending(d => d.CreateTime);

            if (!string.IsNullOrEmpty(title))
            {
                queryable = queryable.Where(u => u.Title.Contains(title));
            }


            //查询总条数
            count = queryable.Count();

            var list = queryable.OrderByDescending(d => d.CreateTime).Skip((page - 1) * limit).Take(limit).ToList()
                .Select(o => new
                {
                    o.Id,
                    o.Title,
                    o.CustomerName,
                    o.CustomerPhone,
                    o.CustomerAddress,
                    o.Area,
                    o.AgentName,
                    o.AgentPhone,
                    StartTime = o.StartTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    EndTime = o.EndTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    o.Designer,
                    CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                }).ToList();

            //查询当前订单id集合
            List<string> orderIds = list.Select(o => o.Id).ToList();

            //查询订单的材料相关信息
            var orderPriceInfos = (from o in _orderMaterialDal.GetDbSet().Where(o => orderIds.Contains(o.OrderId))
                                   join m in _materialDal.GetDbSet()
                                   on o.MaterialId equals m.Id
                                   select new
                                   {
                                       o.OrderId,
                                       o.Num,
                                       m.Price
                                   }).ToList().Select(o => new
                                   {
                                       o.OrderId,
                                       SumPrice = o.Num * o.Price
                                   }).GroupBy(o => o.OrderId).Select(g => new
                                   {
                                       OrderId = g.Key,
                                       TotalPrice = g.Sum(o => o.SumPrice)
                                   }).ToList();

            var returnList = list.Select(o =>
            {
                var data = orderPriceInfos.FirstOrDefault(op => op.OrderId == o.Id);

                return new
                {
                    o.Id,
                    o.Title,
                    o.CustomerName,
                    o.CustomerPhone,
                    o.CustomerAddress,
                    o.Area,
                    o.AgentName,
                    o.AgentPhone,
                    o.StartTime,
                    o.EndTime,
                    o.Designer,
                    o.CreateTime,
                    TotalPrice = data == null ? 0 : data.TotalPrice
                };
            }).ToList();

            return returnList;
        }

        /// <summary>
        /// 获取打印订单数据打印账单
        /// </summary>
        /// <returns></returns>
        public object GetPrintOrderData(string orderId)
        {
            var order = _ordersDal.GetDbSet().FirstOrDefault(o => o.Id == orderId);

            if (order == null)
            {
                return null;
            }

            var list = (from om in _orderMaterialDal.GetDbSet().Where(o => o.OrderId == orderId)
                        join m in _materialDal.GetDbSet().Where(m => !m.IsDelete)
                        on om.MaterialId equals m.Id
                        join c in _classificationDal.GetDbSet().Where(c => !c.IsDelete)
                        on m.ClassificationId equals c.Id
                        select new
                        {
                            ClassificationTitle = c.Title,
                            MaterialTitle = m.Title,
                            m.Unit,
                            om.Num,
                            m.Price,
                            PriceCount = m.Price * om.Num,
                            m.PriceMain,
                            m.PriceAssistant,
                            m.PriceMachine,
                            m.PriceArtificial,
                            m.PriceLoss,
                            MaterialRemark = m.Remark,
                            ClassificationRemark = c.Remark
                        }).ToList().GroupBy(g => g.ClassificationTitle)
                        .Select(g => new
                        {
                            ClassificationTitle = g.Key,
                            ClassificationRemark = g.FirstOrDefault().ClassificationRemark,
                            PriceCount = g.Sum(a => a.PriceCount),
                            List = g.ToList()
                        }).ToList();

            return new
            {
                order.Area,
                order.CustomerName,
                order.CustomerAddress,
                TotalPrice = list.Sum(a => a.PriceCount),
                OrderMaterials = list
            };
        }



        /// <summary>
        /// 更新订单
        /// </summary>
        /// <returns></returns>
        public bool UpdateOrder(string id, string customerName, string customerPhone, string customerAddress, double area, string agentName, string agentPhone, DateTime startTime, DateTime endTime, string designerId, out string msg)
        {
            //根据账号找出订单的信息
            Order entity = _ordersDal.GetDbSet().FirstOrDefault(u => u.Id == id);
            if (entity == null)
            {
                msg = "未找到订单信息";
                return false;
            }

            entity.CustomerName = customerName;
            entity.CustomerPhone = customerPhone;
            entity.CustomerAddress = customerAddress;
            entity.Area = area;
            entity.AgentName = agentName;
            entity.AgentPhone = agentPhone;
            entity.StartTime = startTime;
            entity.EndTime = endTime;
            entity.DesignerId = designerId;

            //调用数据访问层
            bool isSucess = _ordersDal.UpdateEntity(entity);
            msg = "成功";
            return isSucess;
        }


    }
}